package com.atguigu.srb.oss.Service.Impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.atguigu.srb.oss.Service.OssService;
import com.atguigu.srb.oss.utils.OSSProperties;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.UUID;

@Slf4j
@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploda(InputStream inputStream, String module, String FileName) {

        OSS ossclient =new OSSClientBuilder().build(
                OSSProperties.END_POINT,
                OSSProperties.KEY_ID,
                OSSProperties.KEY_SECRET
        );
          //判断这个桶是否存在
        if (!ossclient.doesBucketExist(OSSProperties.BUCKET_NAME)) {
            //设置桶的名字
            ossclient.createBucket(OSSProperties.BUCKET_NAME);
           //设置桶的名字和可读性
            ossclient.setBucketAcl(OSSProperties.BUCKET_NAME, CannedAccessControlList.PublicRead);


        }
        String folder = new DateTime().toString("yyyy/MM/dd");
       FileName= UUID.randomUUID().toString()+FileName.substring(FileName.lastIndexOf("."));
       String key=  module+"/"+folder+"/"+FileName;
       ossclient.putObject(OSSProperties.BUCKET_NAME,key,inputStream);
       return  "https://"+ OSSProperties.BUCKET_NAME+"."+OSSProperties.END_POINT+"/"+key;
      
    }

    @Override
    public void removeFile(String url) {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(
                OSSProperties.END_POINT,
                OSSProperties.KEY_ID,
                OSSProperties.KEY_SECRET);

        //文件名（服务器上的文件路径）
        String host = "https://" + OSSProperties.BUCKET_NAME + "." + OSSProperties.END_POINT + "/";
        String objectName = url.substring(host.length());

        // 删除文件。
        ossClient.deleteObject(OSSProperties.BUCKET_NAME, objectName);

        // 关闭OSSClient。
        ossClient.shutdown();
    }
}
